# markdown.py
from fastapi import APIRouter, HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse
from pathlib import Path

router = APIRouter()

# Markdown 文件夹路径
MARKDOWN_DIR = Path(__file__).parent.parent / "assets" / "markdown"

@router.get("/file/{filename}", response_class=PlainTextResponse)
async def get_markdown_file(filename: str):
    # 防止路径穿越攻击
    safe_filename = Path(filename).name
    
    file_path = MARKDOWN_DIR / safe_filename

    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Markdown 文件未找到")
    
    return file_path.read_text(encoding="utf-8")


@router.get("/list", response_class=JSONResponse)
async def list_markdown_files():
    # 获取文件夹中所有 markdown 文件的名称
    markdown_files = [file.name for file in MARKDOWN_DIR.iterdir() if file.suffix == '.md']
    
    if not markdown_files:
        raise HTTPException(status_code=404, detail="没有找到任何 Markdown 文件")
    
    # 构建响应的 JSON 对象
    return {
        "count": len(markdown_files),
        "data": markdown_files
    }